<script setup lang="ts">
import SingleViewer from '@renderer/views/imgViewer/components/SingleViewer.vue'
import { inject, onActivated, onMounted, ref, onDeactivated, provide, watch } from 'vue'
import OpBtnContainer from '@renderer/views/imgViewer/components/opBtn/OpBtnContainer.vue'
import {
  aspectType,
  EnumAllViewType,
  EnumOpTypes,
  loadSingleViewType,
  opMsgType
} from '@renderer/views/imgViewer/imgTypes'
import axios from 'axios'
import { ISliceInfo } from '@renderer/views/imgViewer/components/types'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useGlobalLoading } from '@renderer/utils/useGlobalLoading'
import { GlobalNotification } from '@renderer/utils/GlobalNotification'
import { useRouter } from 'vue-router'
import { useViewerStatus } from '@renderer/views/imgViewer/useViewerStatus'
import PhaseChoose from '@renderer/views/imgViewer/components/PhaseChoose.vue'

const imgSrcRef = ref('')
const { showLoading, hideLoading } = useGlobalLoading()
const { ioInstance, baseUri, throughGatewayFlag, sendMsg } = inject('pyImgHandlerIo') as any

const phaseInfoRef = ref<any>({
  current: 0,
  total: 1
})

provide('windowId', 'stack')
provide('viewType', EnumAllViewType.stack)
provide('phaseInfo', phaseInfoRef)
provide('activeViewType', EnumAllViewType.stack)
const fourCornerInfoRef = ref({})
const router = useRouter()
const gotImgRef = ref(false)

const sliceInfoRef = ref<ISliceInfo>()

ioInstance.on('image', (data) => {
  if (data?.stack) {
    gotImgRef.value = true
    console.log('收到image,时间是：', new Date().toISOString())
    hideLoading()
    imgSrcRef.value = `${data.stack.img}`
    fourCornerInfoRef.value = data.stack.info_layer
    sliceInfoRef.value = data.stack.slice_info
    phaseInfoRef.value = data.stack.phase_info
  }
})

const aspectRef = ref(null)

const setAspect = async (args: aspectType) => {
  const { width, height } = args
  handleAspectChange(width, height)
  aspectRef.value = {
    width,
    height
  }
}

const handleAspectChange = (width: number, height: number) => {
  if (!gotImgRef.value) {
    return
  }
  const msg = {
    viewType: EnumAllViewType.stack,
    opType: 'resize',
    size: {
      [EnumAllViewType.stack]: {
        width: width,
        height: height
      }
    }
  }
  sendMsg(msg)
}

const setDicomPath = async (dicomPath) => {
  const prefix = throughGatewayFlag ? `${baseUri}/image/` : `${baseUri}/`
  await axios.post(`${prefix}loadPathDicom`, {
    dicom_folder_path: dicomPath
  })
}
const setAspect2Server = async () => {
  const msg: loadSingleViewType = {
    viewType: EnumAllViewType.stack,
    opType: EnumOpTypes.setSize,
    size: aspectRef.value
  }
  const prefix = throughGatewayFlag ? `${baseUri}/image/` : `${baseUri}/`
  await axios.post(`${prefix}setSize`, msg)
}

onMounted(() => {
  console.log('mounted')
  const open = () => {
    ElMessageBox.prompt('输入加载的服务器dicom路径：', 'Tip', {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      // inputValue: 'D:\\test\\py_test_path1'
      // inputValue: 'D:\\test\\test_4d'
      inputValue: 'D:\\test\\py_test_path'
    })
      .then(async ({ value }) => {
        if (!ioInstance.connected) {
          GlobalNotification({
            title: 'Error',
            message: 'Socket io disconnected',
            type: 'error'
          })
          return
        }
        showLoading('加载中')
        await setDicomPath(value)
        await setAspect2Server()
      })
      .catch(() => {})
  }
  open()
})

const goMpr = () => {
  router.push({
    name: 'mpr'
  })
}
const go3d = () => {
  router.push({
    name: 'volume'
  })
}

const { viewStatusRef } = useViewerStatus(EnumAllViewType.stack)

const sendFlipMsg = (hor_flip: boolean, ver_flip: boolean) => {
  const msg: opMsgType = {
    viewType: EnumAllViewType.stack,
    opType: 'flip',
    hor_flip,
    ver_flip
  }
  sendMsg(msg)
}

watch(
  viewStatusRef,
  (newVal) => {
    sendFlipMsg(newVal.horFlip, newVal.verFlip)
  },
  {
    deep: true
  }
)

const handleRotate = (rotateSubType: string) => {
  console.log(`rotate, ${rotateSubType}`)
  const msg: opMsgType = {
    viewType: EnumAllViewType.stack,
    opType: 'rotate',
    subOpType: rotateSubType
  }
  sendMsg(msg)
}

const handleReset = (subResetType: string) => {
  const msg: opMsgType = {
    viewType: EnumAllViewType.stack,
    opType: 'reset',
    subOpType: subResetType
  }
  sendMsg(msg)
}
</script>

<template>
  <div class="w-full h-full flex flex-col">
    <div class="flex w-full h-full">
      <div class="flex-1 h-full w-[900px] h-[600px]">
        <single-viewer
          :view-type="EnumAllViewType.stack"
          @set-aspect="(args) => setAspect(args as aspectType)"
          :img-src="imgSrcRef"
          :fourCornerInfo="fourCornerInfoRef"
          :sliceInfo="sliceInfoRef"
        />
      </div>
      <div class="w-[100px] h-full flex flex-col">
        <op-btn-container
          v-model:viewStatus="viewStatusRef"
          @rotate="handleRotate"
          @reset="handleReset"
        />
        <el-button @click="goMpr" class="w-full">MPR View</el-button>
        <el-button @click="go3d" class="w-full !ml-0">3D View</el-button>
      </div>
    </div>

    <div class="h-[30px] w-full">
      <phase-choose />
    </div>
  </div>
</template>

<style scoped></style>
